package com.bilin.coin.utils;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.core.content.FileProvider;

import com.bilin.coin.ApiConstant;
import com.bilin.coin.common.base.BaseAppCompatActivity;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;


public class ShotShareUtil {

    BaseAppCompatActivity appCompatActivity;

    public ShotShareUtil(BaseAppCompatActivity appCompatActivity) {
        this.appCompatActivity = appCompatActivity;
    }

    /**
     * 截屏分享，供外部调用
     **/
    public void shotShare(BaseAppCompatActivity appCompatActivity) {
        //截屏
        String path = screenShot(appCompatActivity);
        //分享
        if (!TextUtils.isEmpty(path)) {
            ShareImage(appCompatActivity, path);
        }
    }

    /**
     * 截屏分享，供外部调用
     **/
    public void shotShare(BaseAppCompatActivity appCompatActivity, View view) {
        //截屏
        String path = screenShot(appCompatActivity, view);
        //分享
        if (!TextUtils.isEmpty(path)) {
            ShareImage(appCompatActivity, path);
        }
    }

    /**
     * 获取截屏
     **/
    private String screenShot(BaseAppCompatActivity context) {
        String imagePath = null;
        Bitmap bitmap = ScreenUtils.snapShotWithoutStatusBar(context);
        if (bitmap != null) {
            try {
                // 图片文件路径
                imagePath = FilePathUtils.filePath() + "/share.png";

                File file = new File(imagePath);
                FileOutputStream os = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                os.flush();
                os.close();
                return imagePath;
            } catch (Exception e) {
                //LogUtil.e(ShotShareUtil.class, "====screenshot:error====" + e.getMessage());
            }
        }
        return null;
    }

    /**
     * 获取截屏
     **/
    public void screenShot2(BaseAppCompatActivity context, View view) {
        String permission[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        MPermissionUtils.requestPermissionsResult(appCompatActivity, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                String imagePath = null;
                Bitmap bitmap = ScreenUtils.snapShotWithoutStatusBar(context, view);
                if (bitmap != null) {
                    try {
                        // 图片文件路径
                        imagePath = FilePathUtils.filePath() + "/share.png";
                        File file = new File(imagePath);
                        FileOutputStream os = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                        os.flush();
                        os.close();
                        //分享
                        if (!TextUtils.isEmpty(imagePath)) {
                            ShareImage(appCompatActivity, imagePath);
                        }
                    } catch (Exception e) {
                        LogUtlis.e("====screenshot:error====" + e.getMessage());
                    }
                }
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(appCompatActivity);
            }
        }, permission);
    }

    /**
     * 获取截屏
     **/
    private String screenShot(BaseAppCompatActivity context, View view) {
        String imagePath = null;
        Bitmap bitmap = ScreenUtils.snapShotWithoutStatusBar(context, view);
        if (bitmap != null) {
            try {
                // 图片文件路径
                imagePath = FilePathUtils.filePath() + "/share.png";

                File file = new File(imagePath);
                FileOutputStream os = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                os.flush();
                os.close();
                return imagePath;
            } catch (Exception e) {
                LogUtlis.e("====screenshot:error====" + e.getMessage());
            }
        }
        return imagePath;
    }

    /**
     * 分享
     **/
    private void ShareImage(Context context, String imagePath) {
      /*  if (imagePath != null){
            Intent intent = new Intent(Intent.ACTION_SEND); // 启动分享发送的属性
            File file = new File(imagePath);

            //intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));// 分享的内容
            Uri uriForFile = FileProvider.getUriForFile(
                    appCompatActivity,
                    appCompatActivity.getPackageName() + ".fileprovider",
                    file);
            intent.putExtra(Intent.EXTRA_STREAM, uriForFile);// 分享的内容
            intent.setType("image/*");// 分享发送的数据类型
            Intent chooser = Intent.createChooser(intent, "Share screen shot");
            if(intent.resolveActivity(context.getPackageManager()) != null){
                context.startActivity(chooser);
            }
        } else {
            appCompatActivity.showToast("先截屏，再分享");
        }*/

        if (imagePath != null) {
            Intent intent = new Intent(Intent.ACTION_SEND); // 启动分享发送的属性
            File file = new File(imagePath);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                //共享的文件
                Uri apkUri = FileProvider.getUriForFile(context, ApiConstant.PackageName + ".fileProvider", file);
                //授权临时url的文件路径
                //intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                //intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                intent.putExtra(Intent.EXTRA_STREAM, apkUri);// 分享的内容
            } else {

                //intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));// 分享的内容
            }

            intent.setType("image/*");// 分享发送的数据类型
            Intent chooser = Intent.createChooser(intent, "Share screen shot");


            if (intent.resolveActivity(context.getPackageManager()) != null) {
                context.startActivity(chooser);
            }
        } else {
            appCompatActivity.showToast("先截屏，再分享");
        }

    }

    public static String viewSaveToImage(@NotNull Context context, View view) {
        boolean success = false;
        String savePath = "";
        try {
            Bitmap bm = ((BitmapDrawable) ((ImageView) view).getDrawable()).getBitmap();
            String fileName = /*Calendar.getInstance().getTimeInMillis() +*/ ApiConstant.SavePicName;
            savePath = FilePathUtils.filePath() + "/" + fileName;
            File outFile = new File(savePath);
            success = FilePathUtils.saveBitMap(bm, outFile);
        } catch (Exception e) {
            LogUtlis.e(e.getMessage());
        }
        // 把文件插入到系统图库
      /*  try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    outFile.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            success = false;
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + outFile.getPath())));*/
        return success ? savePath : "";
    }

    /**
     * 截屏分享，供外部调用
     **/
    public void shotShare2(BaseAppCompatActivity appCompatActivity, View view) {
        //截屏
        String path = viewSaveToImage(appCompatActivity, view);
        //分享
        if (!TextUtils.isEmpty(path)) {
            ShareImage(appCompatActivity, path);
        } else {
            appCompatActivity.showToast("保存失败");
        }
    }
}
